package osu.cloudmonitor;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Responser extends Thread {
	
	public static void main(String []args) throws Exception{
		if(args.length != 1){
			System.err.println("java Responser <port>");
			return;
		}
		int port = Integer.parseInt(args[0]);
		new AcceptThread(port).start();
		while(true){
			try{
				Thread.sleep(60000);
			}
			catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}
	
	private static class AcceptThread extends Thread{
		
		private int port;
		private ServerSocket ss = null;
		private boolean running = true;
		
		public AcceptThread(int port){
			this.port = port;
		}
		
		public void run(){
			while(true){
				try{
					if(ss==null){
						ss = new ServerSocket(port);
						System.out.println("Binded to "+port);
					}
					while(true){
						Socket s = ss.accept();
						new ResponserThread(s).start();
					}
				}
				catch(Exception e){
					e.printStackTrace();
					try{
						Thread.sleep(10000);
					}
					catch(InterruptedException ie){}
				}
			}
		}
	}
	
	private static class ResponserThread extends Thread{
		private Socket socket = null;
		public ResponserThread(Socket socket){
			this.socket = socket;
		}
		
		public void run(){
			try{
				DataInputStream dis = new DataInputStream(socket.getInputStream());
				int bytes = dis.readInt();
				if(bytes > Configuration.MAX_PACKET_SIZE)
					System.out.println("Too large "+bytes);
				socket.getOutputStream().write(new byte[bytes]);
				socket.getOutputStream().flush();
				socket.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
	}

}


